
#ifndef __THREAD_POOL_H
#define __THREAD_POOL_H

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>
#include <signal.h>

#include "xs_tsqueue.h"

#ifndef BOOL
#define BOOL int
#endif

#ifndef TRUE
#define TRUE 1
#endif

#ifndef FALSE
#define FALSE 0
#endif

#define BUSY_THRESHOLD 0.5	//(busy thread)/(all thread threshold)
#define MANAGE_INTERVAL 30	//tp manage thread sleep interval, every MANAGE_INTERVAL seconds, manager thread will try to recover idle threads as BUSY_THRESHOLD


typedef void (*xs_work)(void *arg);
typedef struct __xs_thread_info__ xs_thread_info;
typedef struct __xs_thread_pool__ xs_thread_pool;

struct __xs_thread_pool__ {
    int mininum;     	/* Minum number of threads in the pool */
    int current;     		/* Current thread count in the thread pool */
    int maxinum;     	/* Maxinum number of threads in the pool */
    int exitted;     		/* How many threads in this thread pool have been exited */
    int tasks;
    xs_pthread_mutex_t threadpool_mutex;
    xs_pthread_cond_t threadpool_cond;
    xs_pthread_mutex_t threadpool_exit_mutex;
    xs_pthread_cond_t threadpool_exit_cond;

    xs_thread_info *thread_info;    /* all the thread information */
    xs_queue *idle; 	/* idle queue */
    BOOL stop; 	/* whether stop the threading pool or not */

    xs_pthread_t manage_thread;     /* manage thread id num */
    float busy_threshold;           /* */
    unsigned manage_interval;       /* */
};

struct __xs_thread_info__{
    xs_pthread_t thread_id; //thread id num
    BOOL is_busy; //thread status:true-busy;flase-idle
    xs_pthread_cond_t thread_cond;
    xs_pthread_mutex_t thread_mutex;
    xs_work func;
    void *arg;
    xs_thread_pool *threadpool;
};


xs_thread_pool *	xs_threadpool_create(unsigned , unsigned );
void 			xs_threadpool_run(xs_thread_pool *);
void 			xs_threadpool_close(xs_thread_pool *, BOOL );
int 				_xs_work(xs_thread_pool *, xs_work , void *);
float 			xs_get_busy_threshold(xs_thread_pool *);
int 				xs_set_busy_threshold(xs_thread_pool *, float );
unsigned 			xs_get_manage_interval(xs_thread_pool *);
int 				xs_set_manage_interval(xs_thread_pool *, unsigned ); //mi - manager interval time, in second


int 				xs_threadpool_entry(int argc, char **argv);

#endif
